package com.codejoys.ssm.web;

import com.codejoys.ssm.dto.BaseReponse;
import com.codejoys.ssm.entity.Daily;
import com.codejoys.ssm.service.DailyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class DailyController {
    @Autowired
    DailyService service;

    //不能写，不然都访问不了
//    @GetMapping("/")
//    public String home(){
//        return "index.html";
//    }

    @GetMapping("/hello")
    public String hello(){
        System.out.println("hello...");
        return "index.html";
    }

    /**
     * 写接口
     * 1.对应的url路径 2.请求有哪些参数 3.要返回哪些数据
     * 请求路径：/daily/list
     * 参数：没有
     * 返回数据：
     * [
     *    {"id","tilte":"xxx","created":"2018-10-10"},
     *    {"id","tilte":"xxx","created":"2018-10-10"}
     * ]
     */

    @GetMapping("/daily/list")
    @ResponseBody //直接把java对象序列化成json字符串
    public List<Daily> findAll(){
        List<Daily> data = service.findAll();
//        data.forEach(daily->{
//            System.out.println(daily);
//        });
//        return "index.html";//TODO

        return data;
    }

    /**
     *{
     *   "count":76,   //数据条数，分页
     *   "code":0,     //响应码，返回0认为响应成功
     *   "message":"响应成功"
     *   [
     *     {"id","tilte":"xxx","created":"2018-10-10"},
     *     {"id","tilte":"xxx","created":"2018-10-10"}
     *   ]
     * }
     */
    @GetMapping("/daily/all")
    @ResponseBody
    public BaseReponse findList(){
        List<Daily> list = service.findAll();

        Long count = service.count();

        BaseReponse response = new BaseReponse();
        response.setCode(0L);
        response.setMsg("成功");
        response.setCount(count);
        response.setData(list);

        return response;
    }

    /**
     *路径：  /daily
     *参数：  id=1
     *返回结果：
     * {"id":1,"tilte":"xxx","created":"2018-10-10"}
     */
    @GetMapping("/daily")
    @ResponseBody
    public Daily findById(@RequestParam("id")Integer sid){
        return service.findById(sid);
    }
}
